import os
from qcloud_cos import CosConfig, CosS3Client
from common import get_logger

logger = get_logger(__name__)
from config import (
    TENCENT_SECRET_ID,
    TENCENT_SECRET_KEY,
    TENCENT_REGION,
    TENCENT_BUCKET,
    TENCENT_SCHEME,
    TENCENT_TOKEN,
)


def upload_to_cos(file_path):
    # 用文件名作为保存的key
    key = os.path.basename(file_path)
    config = CosConfig(
        SecretId=TENCENT_SECRET_ID,
        SecretKey=TENCENT_SECRET_KEY,
        Region=TENCENT_REGION,
        Scheme=TENCENT_SCHEME,
        Token=TENCENT_TOKEN,
    )
    # 创建客户端实例
    client = CosS3Client(config)
    with open(file_path, "rb") as file:
        client.put_object(
            Bucket=TENCENT_BUCKET,
            Body=file,  # 文件的二进制内容
            Key=key,  # 保存的key
            StorageClass="STANDARD",
            EnableMD5=False,  # 禁用MD5较验
        )
    url = f"https://{TENCENT_BUCKET}.cos.{TENCENT_REGION}.myqcloud.com/{key}"
    logger.info(f"文件已经上传，访问地址为:{url}")
    return url
